package net.zhongfu.flowable.helper.common.configuration;

import net.zhongfu.flowable.helper.common.utils.DatabaseUtils;
import net.zhongfu.flowable.helper.common.utils.StringUtils;
import net.zhongfu.flowable.helper.database.DmDatabase;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;


/**
 * @Description: 配置流程引擎
 * @Author: fsrong
 * @Date: 2021/7/13 16:56
 */
@Configuration
public class DefaultEngineConfiguration implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {

    private static final Logger logger = LoggerFactory.getLogger(DefaultEngineConfiguration.class);

    /**
     * @Description: 默认引擎配置
     * @param processEngineConfiguration
     * @Author: fsrong
     * @Date: 2021/7/14 9:05
     */

    @Override
    public void configure(SpringProcessEngineConfiguration processEngineConfiguration) {
        try {
            Connection connection = processEngineConfiguration.getDataSource().getConnection();
            String productName = DatabaseUtils.getProductName(connection);
            if(DmDatabase.PRODUCT_NAME.equalsIgnoreCase(productName)) {
                // 达梦数据库需要设置schema，优先使用配置的
                String schema = connection.getSchema();
                processEngineConfiguration.setDatabaseSchema(StringUtils.defaultString(processEngineConfiguration.getDatabaseSchema(),schema));
            }
            // 扩展数据库类型
            DatabaseUtils.databaseTypeExtend(processEngineConfiguration,processEngineConfiguration.getClass().getSuperclass());
            // 数据库类型注册，扩展国产数据库
            DatabaseUtils.registrar(processEngineConfiguration.getDataSource());
        } catch (Exception throwables) {
            logger.error("Flowable适配数据库错误",throwables);
        }
        logger.info("Flowable适配数据库完成 ");
    }
}
